﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Drawing;
using System.Drawing.Drawing2D;
using ImageDrawing = System.Drawing.Image;

namespace BlogPlat.Areas.Admin.Controllers
{
    public class UploadController : Controller
    {
        #region Images
        //
        // GET: /Admin/Upload/
        public ActionResult Index()
        {
            ViewData["CKEditorFuncNum"] = Request.QueryString["CKEditorFuncNum"];
            ViewData["CKEditor"] = Request.QueryString["CKEditor"];
            ViewData["langCode"] = Request.QueryString["langCode"];

            var dirPath = Path.Combine(Server.MapPath("~/Content/UploadImages/" + User.Identity.Name));
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            string[] fileNames = Directory.GetFiles(dirPath);            
            List<FileInfo> images = new List<FileInfo>();
            foreach (string filename in fileNames)
            {
                FileInfo image = new FileInfo(filename);
                images.Add(image);                
            }
            return View(images);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
        {            
            if (file.ContentLength > 0)
            {
                var dirPath = Path.Combine(Server.MapPath("~/Content/UploadImages/" + User.Identity.Name));
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(dirPath, fileName);
                file.SaveAs(path);                                                
            }

            RouteValueDictionary rvd = new RouteValueDictionary();
            rvd.Add("CKEditorFuncNum", CKEditorFuncNum);
            rvd.Add("CKEditor", CKEditor);
            rvd.Add("langCode", langCode);

            return RedirectToAction("Index", rvd);
        }        
    
        public ActionResult Images(string id)
        {
            // So that I don't need to specify another route.
            string filename = id;

            // Get image filename from Request object.             
            string photoFolder = Server.MapPath("~/Content/UploadImages/" + User.Identity.Name);
            filename = Path.Combine(photoFolder, filename);
            int width = 150; int height = 150;
            string bg = "#ffffff";

            StreamReader r = new StreamReader(filename);
            ImageDrawing thumbnail = ImageDrawing.FromStream(r.BaseStream);

            MemoryStream ms = new MemoryStream();
            thumbnail = Scale(thumbnail, width, height, bg); 
            thumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            byte[] imageByte = ms.ToArray();

            ms.Dispose();
            thumbnail.Dispose();            
            r.Dispose();

            return File(imageByte, "image/jpeg");
        }

        /// <summary>
        /// Resizes images to the specified width and height, it also adds background color.
        /// </summary>
        /// <param name="imgPhoto">Image object</param>
        /// <param name="Width">Target width</param>
        /// <param name="Height">Target Height</param>
        /// <param name="bg">Background color in format (#000000)</param>
        /// <returns></returns>
        private static ImageDrawing Scale(ImageDrawing imgPhoto, int Width, int Height, string bg)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = Convert.ToInt16((Width - (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((Height - (sourceHeight * nPercent)) / 2);
            }
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            Color c = System.Drawing.ColorTranslator.FromHtml(bg);

            grPhoto.Clear(c);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight),
              new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
        #endregion

        public ActionResult Files()
        {
            return View();
        }

        public ActionResult FileUpload()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/UploadFiles"), fileName);
                file.SaveAs(path);
            }

            return RedirectToAction("Index");
        }
    }
}
